#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <sys/socket.h>
#include <pthread.h>
#include <sys/wait.h>
#include <signal.h>

#include "err_handling.h"
#include "read_child.h"

#define BUF_SIZE 256

int main(int argc, char *argv[])
{
    int serv_sock, clnt_sock;
    int recv;
    struct sockaddr_in serv_adr, clnt_adr;
    int clnt_adr_sz;
    char msg_recv[BUF_SIZE], msg_send[BUF_SIZE];
    char name[20];
    pid_t pid;
    struct sigaction act;
    act.sa_handler = read_childproc;
    sigemptyset(&act.sa_mask);
    act.sa_flags = 0;
    sigaction(SIGCHLD, &act, NULL);

    if (argc != 2)
    {
        printf("Usage:%s <port>\n", argv[0]);
        exit(0);
    }

    serv_sock = socket(PF_INET, SOCK_STREAM, 0);

    memset(&serv_adr, 0, sizeof(serv_adr));
    serv_adr.sin_family = AF_INET;
    serv_adr.sin_addr.s_addr = htonl(INADDR_ANY);
    serv_adr.sin_port = htons(atoi(argv[1]));

    if (bind(serv_sock, (struct sockaddr *)&serv_adr, sizeof(serv_adr)) == -1)
        error_handling("bind() error");
    if (listen(serv_sock, 5) == -1)
        error_handling("listen() error");

    while (1)
    {
        clnt_adr_sz = sizeof(clnt_adr);
        clnt_sock = accept(serv_sock, (struct sockaddr *)&clnt_adr, &clnt_adr_sz);
        pid = fork();
        if (pid == -1)
            error_handling("fork() error");
        if (pid == 0)
        {
            // close(serv_sock);
            while (1)
            {
                fgets(msg_send, BUF_SIZE, stdin);
                write(clnt_sock, msg_send, 256);
            }
        }
        else
        {
            // close(clnt_sock);
            while (1)
            {
                recv = read(clnt_sock, msg_recv, 256);
                if (recv == 0)
                    break;
                if (!strcmp(msg_recv, "q\n") || !strcmp(msg_recv, "Q\n"))
                {
                    printf("Client typed Q to disconnected\n");
                    shutdown(clnt_sock, SHUT_WR);
                    break;
                }
                msg_recv[recv] = 0;
                printf(">>>message from client:%s", msg_recv);
            }
        }
    }
    close(serv_sock);
    return 0;
}